<template>
  <div>
    <el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
      <el-breadcrumb-item :to="{ path: '/ManageHome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>内容管理</el-breadcrumb-item>
      <el-breadcrumb-item>路线信息</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin: 15px; min-height: calc(100vh - 111px)">
      <div>
        <!--    功能区-->
        <div style="margin: 10px 0">
          <!--    搜索区-->
          <div style="margin: 10px 0">
            <span style="margin-left: 40px; margin-right: 14px; font-size: 15px; font-weight: 700;">路线名称</span>
            <el-input v-model="search"  size="small" clearable placeholder="请输入活动名称" prefix-icon="el-icon-search" style="width: 15%;" />
           
            <el-button icon="el-icon-search" @click="load"
              style="background-color: #143371; color: aliceblue;" size="small">搜索</el-button>
            <el-button icon="el-icon-refresh-left" style="margin-left: 5px;"
              @click="reset" size="small">重置</el-button>
            <div style="float: right">

              <el-tooltip content="添加路线信息" placement="top">

                <el-button style="background-color: #143371; color: aliceblue;" size="small"
                  @click="add">+新增</el-button>
              </el-tooltip>
            </div>
          </div>
        </div>
        <!--    表格-->
        <el-table v-loading="loading" :data="tableData" max-height="1000" style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="路线名称">
                  <span>{{ props.row.routeName }}</span>
                </el-form-item>
                <el-form-item label="游玩天数">
                  <p>{{ props.row.routeDay }}</p>
                </el-form-item>
              
                <el-form-item label="适玩季节">
                  <p>{{ props.row.routeSeason }}</p>
                </el-form-item>
                <el-form-item label="路线封面">
                  <img :src="props.row.routeCoverImg" alt="" style="width: 180px; height: 150px;">
                </el-form-item>
                <el-form-item label="更多图片">
                  <div style="display: flex;">
                    <img :src= "item" alt="" v-for="(item, index) in props.row.routeImags"
                      :key="index" style="width: 180px; height: 150px;">
                  </div>
                </el-form-item>
                <el-form-item label="详细介绍">
                  <div v-html="props.row.routeContent"></div>
                </el-form-item>


              </el-form>
            </template>
          </el-table-column>


          <el-table-column label="#" type="index" />
          <el-table-column label="编号" prop="routeId" />
          <el-table-column label="路线名称" prop="routeName"  />
          <el-table-column label="封面" width="150px">
            <template slot-scope="scope">
              <img :src="scope.row.routeCoverImg" alt="" style="width: 120px; height: 90px;">
            </template>
          </el-table-column>
          <el-table-column label="游玩天数" prop="routeDay"/>
          <el-table-column label="适玩季节" prop="routeSeason" />
       
      
         
          <!--      操作栏-->
          <el-table-column label="操作" width="150px">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div style="margin: 10px 0">
          <el-pagination :currentPage="currentPage" :page-size="pageSize" :page-sizes="[5, 10]" :total="total"
            layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
          </el-pagination>
        </div>
        <div>
          <!--      弹窗-->
          <el-dialog :visible.sync="dialogVisible" title="操作" width="50%" @close="cancel" top="30px">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          
              <el-form-item label="名称" prop="routeName">
                <el-input v-model="form.routeName" style="width: 80%" placeholder="路线名称"></el-input>
              </el-form-item>

              <el-form-item label="游玩天数" prop="routeDay">
                <el-input v-model.number="form.routeDay" style="width: 80%" placeholder="填写游玩天数"></el-input>
              </el-form-item>

              <el-form-item label="适玩季节" prop="routeSeason">
                <el-input v-model="form.routeSeason" style="width: 80%" placeholder="填写季节"></el-input>
              </el-form-item>
              <el-form-item label="封面图" prop="routeCoverImage">
                <el-upload action="" list-type="picture-card" :limit="1" :on-preview="handlePictureCoverPreview"
                  :on-remove="handleCoverRemove" accept=".jpg,.png" :on-exceed="handleExceed" :file-list="cover_list"
                  :http-request="UploadCover">
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="CoverdialogVisible">
                  <img width="100%" :src="CoverdialogImageUrl" alt="">
                </el-dialog>

              </el-form-item>
              <el-form-item label="活动图片(最多9张)" prop="routeImages">
                <el-upload action="" list-type="picture-card" :limit="9" :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove" accept=".jpg,.png" :on-exceed="handleNineExceed" :auto-upload="true"
                  :file-list="more_list" :http-request="UploadMore" multiple>
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="MoredialogVisible">
                  <img width="100%" :src="MoredialogImageUrl" alt="">
                </el-dialog>

              </el-form-item>

              <el-form-item label="详细介绍" prop="routeContent">
                <div style="border: 1px solid #ccc;">
                  <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
                    :mode="mode" />
                  <Editor style="height: 500px; overflow-y: hidden;" v-model="form.routeContent" :defaultConfig="editorConfig"
                    :mode="mode" @onCreated="onCreated" />
                </div>
              </el-form-item>

            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script>
import request from '@/utils/request'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
export default {
  components: { Editor, Toolbar },
  data() {
    

    return {
   
      dialogloading: false,
      cover_list: [],
      more_list: [],
      CoverdialogImageUrldialogImageUrl: '',
      CoverdialogVisible: false,
      MoredialogImageUrl: '',
      MoredialogVisible: false,
      editor: null,
      toolbarConfig: {},
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default',

      value:'',
      loading: true,
      editJudge: true,
      judge: false,
      dialogVisible: false,
      search: "",
      currentPage: 1,
      pageSize: 5,
      total: 0,

      tableData: [
        {
          routeId: 1,
          routeName: '张家界森林公园',
          routeDay: 2,
          routeContent: '<h4>111111111<h4>',
          routeImags: ['lhs3.jpg', 'ls1.jpg', 'sqs6.jpg'],
          routeCoverImg: 'lhs4.jpg',
          routeSeason:'秋季'
         
        }
      ],
      form: {
          routeId: 1,
          routeName: '张家界森林公园',
          routeDay: 2,
          routeContent: '<h4>111111111<h4>',
          routeImags: ['lhs3.jpg', 'ls1.jpg', 'sqs6.jpg'],
          routeCoverImg: 'lhs4.jpg',
          routeSeason:'秋季'
         
        },
      rules: {
      
        routeName: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
       
        routeContent: [{ required: true, message: "请输入介绍", trigger: "change" }],
      
       
        routeSeason: [
         
          { required: true, trigger: "blur" ,message:'请输入游玩季节'}
        ],
        routeDay:[
          {
            required: true, message: "请选择日期", trigger: "blur"
          },
          { type: "number", message: "游玩天数必须为数字", trigger: "blur" },
        ]
      },
      editDisplay: {
        display: "block",
      },
      display: {
        display: "none",
      },
    };
  },
  created() {
    this.load();
    this.loading = true;
    setTimeout(() => {
      //设置延迟执行
      this.loading = false;
    }, 1000);
  },
  beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    },
  methods: {
    onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
        },
    UploadCover(data){
      var formData = new FormData()
      formData.append('type','route')
      formData.append('file',data.file)
      this.dialogloading = true
      console.log("图片文件",data)
      console.log("现在的图片",this.cover_list)
      request.post("/scenery/upload",formData).then(res=>{
        if(res.code==='1'){
          this.cover_list = []
          this.cover_list.push({name:data.file.name,url:res.data})
          this.dialogloading = false;
        }else{
          this.dialogloading = false
          this.$message({
            type:'error',
            message:'上传失败'
          })
        }
      
      })

      
    },
    UploadMore(data){
      var formData = new FormData()
      formData.append('type','route')
      formData.append('file',data.file)
      this.dialogloading = true;
      console.log("上传详细图片",data)
      console.log("现在的图片",this.more_list)
      request.post("/scenery/upload",formData).then(res=>{
        if(res.code==='1'){
         // this.cover_list = []
         
          this.more_list.push({name:data.file.name,url:res.data})
          this.dialogloading = false;
        }else{
          this.dialogloading = false
          this.$message({
            type:'error',
            message:'上传失败'
          })
        }
      
      })
    },
    handleRemove(file, fileList) {
      console.log("删除",file, fileList);
      this.more_list = this.more_list.filter(item=>{
        return item.name!=file.name
      })
    },
    handleCoverRemove(file,fileList){
      console.log("删除",file, fileList);
      this.cover_list = []
    },
    handlePictureCoverPreview(file){
      this.CoverdialogImageUrldialogImageUrl = file.url;
      this.CoverdialogVisible = true;
    },
    handlePictureCardPreview(file) {
      this.MoredialogImageUrl = file.url
      this.MoredialogVisible = true
    },

    handleExceed(){
      this.$message.warning(`只允许上传一张图片`);
    },
    handleNineExceed(){
      this.$message.warning(`只允许上传9张图片`);
    },
    async load() {
      
      await request.get("/route/adminlist", {
            params: {
                pageNum: this.currentPage,
                pageSize: this.pageSize,
                search: this.search,
            },
        }).then((res) => {
            console.log(res);
            this.tableData = res.data.list;
            this.total = res.data.total;
            this.loading = false;
        });
    },
 
    reset() {
      this.search = ''
     
      this.currentPage = 1;

      this.pageSize = 10

      this.load()
    },

    handleDelete(index, row) {
      // 确认框确认是否要删除
      this.$confirm("确定要删除" + row.routeName + "的信息吗?", "删除提示", {
        iconClass: "el-icon-question", //自定义图标样式
        confirmButtonText: "残忍删除", //确认按钮文字
        cancelButtonText: "取消删除", //取消按钮文字
        showClose: true, //是否显示右上角关闭按钮
        type: "warning", //提示类型  success/info/warning/error
      }).then(() => {  //选择确认按钮进入此方法
        request.delete("/activity/delete/" + row.routeId).then(res => {
          
          if (res.code === "1") {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.load()
          }
          else {
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
        })
      }).catch(() => { //选择取消按钮进入此方法
        //取消操作
        alert('取消')
      });
    },
    handleEdit(index, row) {
      this.judge = true;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
        this.form = JSON.parse(JSON.stringify(row));
         //gaiiiiiiiiiiiii
        this.cover_list.push({name:"route",url:this.form.routeCoverImg})
       
        this.form.routeId = parseInt(this.form.routeId)

        for(var i =0;i<this.form.routeImags.length;i++){
          this.more_list.push({name:'route'+i,url:this.form.routeImags[i]})
        }
        this.editDisplay = { display: "block" };
      });
    },
    cancel() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
      this.cover_list=[]
      this.more_list=[]
    },
    save() {
      this.$refs.form.validate(vaild => {
        if (vaild) {
          if (this.judge) {
            //先表单验证，再放put请求
            this.form.routeCoverImg = this.cover_list[0].url
            this.form.routeImags = []
           
            for(var i=0;i<this.more_list.length;i++){
              
              this.form.routeImags.push(this.more_list[i].url)
             
            }
            request.put("/route/update", this.form).then(res => {
              if (res.code === "1") {
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                 //gaiiiiiiiiiiiii
                this.search = "",
              
                this.load();
                this.dialogVisible = false
              }
              else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            })


          }
          else {
            //发post请求
             //gaiiiiiiiiiiiii
            this.form.routeCoverImg = this.cover_list[0].url
            this.form.routeImags = []
           
            for(var i=0;i<this.more_list.length;i++){
              
              this.form.routeImags.push(this.more_list[i].url)
             
            }
           
            request.post("/route/add", this.form).then(res => {
              if (res.code === "1") {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.search = "",
                this.load();
                this.dialogVisible = false
              }
              else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            })
          }
        }
      })


    },
    add() {
      this.dialogVisible = true;
      this.judge = false;
      this.form = {}
    },
    handleSizeChange(pageSize) {
      //改变每页个数
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      //改变页码
      this.currentPage = pageNum;
      this.load();
    },

  }


}
</script>
<style>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 80%;
  display: block;
}
</style>